var LoginMethod = (function () {
    var instance;

    function init() {
        // 单例
        // 私有方法和变量
        var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        var base64DecodeChars = new Array(-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1);

        var param = Util.GetRequest();

        function loginNormal(fun) {
            NetHttp.loginByToken(param['uuid']).then(function (res) {
                var data = res.data;
                if (data.code == 200) {
                    var resData = data.data;
                    console.log(resData)
                    userInfo.setUserData(resData); 
                    userInfo.setToken(resData.token);
                    fun('loginSuccess');
                } else {
                    var msg = '';
                    if (data) {
                        msg = data.msg;
                    }
                    fun('loginFailed');
                }
            }).catch(function (err) {
                console.log("err:", err);
                if (err.message.indexOf('Network Error') >= 0) {
                    fun('loginFailed');
                    return;
                }
                fun('loginFailed');
            });
        }
        function loginWeChat(fun) {
            var code = userSpace.code;
            var token = laya.net.LocalStorage.getItem('token');
            NetUtil.get('/weixin/login', {
                code: code,
                token: token,
                roomId: userSpace.roomId,
                tick: userSpace.tick,
                gameType: 'paijiu',
                xxCode: userSpace.xxCode,
            }, function (sur, res) {
                console.log('res', res);
                if (res && res.code == 200) {
                    console.log('wechat login success')
                    userInfo.setUserData(res);
                    userInfo.setToken(res.token);
                    fun('loginSuccess');
                    // wxConfig();
                } else {
                    var msg = '';
                    if (res) msg = res.msg;
                    fun('loginFailed');
                }
            }.bind(this));
        }
        function LoginWeiXin(fun) {
            var param = Util.GetRequest();;
            var code = param['code'];
            var xxCode = param['xxCode'];
            userSpace.code = code;
            userSpace.xxCode = xxCode;
            var token = laya.net.LocalStorage.getItem('token');
            var guesttoken = laya.net.LocalStorage.getItem('guesttoken');
            userSpace.guesttoken = guesttoken;
            userSpace.token = token;
            userSpace.ownerUid = param['uid'];
            userSpace.uuid = param['uuid'];
            userSpace.roomId = param['roomId'];
            var tick = param['tick'];
            userSpace.roomTick = tick;
            userSpace.tick = tick;
            var name = param['name'];
            userSpace.urlName = name;
            var imgurl = param['headimgurl'];
            userSpace.imgurl = imgurl;
            var retick1 = laya.net.LocalStorage.getItem("retick");
            var retick2 = param["retick"];
            var action = param['action'];
            this.roomOwnerName = decodeURIComponent(base64decode(name));
            //this.roomOwnerHeadimgurl=decodeURIComponent(this.base64decode(imgurl));
            this.roomOwnerName = name;
            this.roomOwnerHeadimgurl = imgurl;
            if (action === "clear") {
                console.log("clear cache token")
                laya.net.LocalStorage.setItem('guesttoken', "");
                laya.net.LocalStorage.setItem('token', "");
                token = null;
                guesttoken = null;
                userSpace.token = null;
                userSpace.guesttoken = null;
            }
            if (getIsWeChatClient() && xxCode)

                if (xxCode && !token && !userSpace.uuid) {
                    loginWeChat(fun);
                    return;
                }
            if (getIsWeChatClient() && !code && !token && !userSpace.uuid) {
                if (Util.IsNative()) {
                    if (JSandOC) {
                        JSandOC.js_sy_Wxauthorize();
                    }
                } else {
                    redirectWxAuth();
                }
                return;
            }
            if (getIsWeChatClient() && (code && !token) && !userSpace.uuid) //微信登录返回的code
            {
                loginWeChat(fun);
                return;
            }
        }
        function redirectWxAuth() {
            var tick = new Date().getTime() + "_" + Math.floor(Math.random() * 1000);
            var url0 = Util.getCurrentWebDir() + "h5_fk_hall/game.html?tick=" + new Date().getTime();
            var url = appConfig.authAddr + "/route.html?redirect=" + encodeURIComponent(url0);
            window.location.replace(url);
            return;
        }
        /**
         * 判断是否是微信环境
         */
        function getIsWeChatClient() {
            var ua = navigator.userAgent.toLowerCase();
            if (ua.match(/MicroMessenger/i) == "micromessenger") {
                return true;
            }
            return false;
        }

        /**
         * base64解码
         * @param {Object} str
         */
        function base64decode(str) {
            var c1, c2, c3, c4;
            var i, len, out;
            if (!str) return '';
            len = str.length;
            i = 0;
            out = "";
            while (i < len) {
                /* c1 */
                do {
                    c1 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
                }
                while (i < len && c1 == -1);
                if (c1 == -1)
                    break;
                /* c2 */
                do {
                    c2 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
                }
                while (i < len && c2 == -1);
                if (c2 == -1)
                    break;
                out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4));
                /* c3 */
                do {
                    c3 = str.charCodeAt(i++) & 0xff;
                    if (c3 == 61)
                        return out;
                    c3 = base64DecodeChars[c3];
                }
                while (i < len && c3 == -1);
                if (c3 == -1)
                    break;
                out += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2));
                /* c4 */
                do {
                    c4 = str.charCodeAt(i++) & 0xff;
                    if (c4 == 61)
                        return out;
                    c4 = base64DecodeChars[c4];
                }
                while (i < len && c4 == -1);
                if (c4 == -1)
                    break;
                out += String.fromCharCode(((c3 & 0x03) << 6) | c4);
            }
            return out;
        }


        function loginByGuest(action, cb) {
            var self = this;
            get('/weixin/gameGuestLogin', {
                guesttoken: userInfo.getToken(),
                uid: userInfo.getUid(),
                gameType: appConfig.gameType
            }, function (suc, res) {
                if (res && res.code == 200) {
                    console.log('guest login success')
                    console.log('游戏地址1：');
                    console.log(res);
                    userSpace.loginRes = res;
                    userSpace.token = res.token;
                    laya.net.LocalStorage.setItem('token', res.token);
                    cb('loginSuccess', '');
                    //node.icon='http://weixin.g9527.com/weixin/getimg?imgurl='+encodeURIComponent(res.headimgurl)+"&type=img.jpg";

                }
                else {
                    var msg = '';
                    if (res) msg = res.msg;
                    cb('loginFailed', msg);
                }
            });
        }

        function post(route, args, cb) {
            //return;
            var res = userSpace.loginRes;
            if (!res) return;
            //if(!res.debugFlag)  return;
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    //this.logining=0;
                    if (xhr.status === 200) {
                        var res;
                        try {
                            res = JSON.parse(xhr.responseText);//{"code":200,"token":"427333eb9ab047341478b246fc458c78","uid":"8","diamond":"0","coin":"0"}
                            var len = xhr.responseText.length;
                            if (len < 200)
                                console.log('res', xhr.responseText);
                            if (res.code == 200) { if (cb) cb('success', res); }
                            else { if (cb) cb('failed', res); }
                        }
                        catch (e) {
                            cb('err', xhr.responseText);
                        }

                    }
                    else { cb('failed', null); }
                }
            };
            var webAddr = appConfig.webAddr;
            var param = '';
            var token = localStorage.getItem("token")
            if (userSpace.loginRes) {
                token = userSpace.loginRes.token;
            }
            if (typeof args == 'object')
                args["token"] = token;

            if (typeof args == 'string') param = args;

            if (typeof args == 'object')
                for (var k in args) {
                    var value = args[k];
                    if (value == undefined) continue;
                    if (typeof value == 'object') value = JSON.stringify(args[k]);
                    param = param + k + '=' + value + '&';
                }
            //var str=JSON.stringify(formData);
            var random = 'random=' + new Date().getTime();
            var url = webAddr + route + '?' + random;
            if (url.indexOf('http://') < 0) url = 'http://' + url;
            xhr.open("post", url);
            xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
            var s = JSON.stringify(args);
            xhr.send(s);
        };

        function get(route, args, cb) {
            var webAddr = appConfig.gameUrl;
            if (typeof args != 'object') {
                if (cb) cb('invalid args', null);
                return;
            }
            var self = this;
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    //this.logining=0;
                    if (xhr.status === 200) {
                        var res;
                        try {
                            res = JSON.parse(xhr.responseText);//{"code":200,"token":"427333eb9ab047341478b246fc458c78","uid":"8","diamond":"0","coin":"0"}
                            var len = xhr.responseText.length;
                            if (len < 200)
                                console.log('res', xhr.responseText);
                            if (res.code == 200) {
                                if (cb) cb('success', res);
                            } else {
                                if (cb) cb('failed', res);
                            }
                        } catch (e) {
                            console.log('error', e.message, e.stack);
                            cb('str', xhr.responseText);
                        }

                    } else {
                        cb('failed', null);
                    }
                }
            };
            var formData = {};
            var param = '';
            if (userSpace.loginRes) {
                if (userSpace.loginRes.token) { args["token"] = userSpace.loginRes.token; }
                else {
                    var token = localStorage.getItem("token");
                    args["token"] = token;
                }
            }

            for (var k in args) {
                if (args[k] == undefined) continue;
                param = param + k + '=' + args[k] + '&';
            }
            //var str=JSON.stringify(formData);
            var random = 'random=' + new Date().getTime();
            var url = webAddr + route + '?' + param + random;
            if (url.indexOf('http://') < 0) url = 'http://' + url;
            xhr.open("get", url);
            xhr.setRequestHeader("Content-Type", "text/javascript;charset=UTF-8");
            xhr.send('data');
        };

        return {
            checkUrl: function (fun) {
                //调试模式登录
                if (param['uuid']) {
                    console.log('调试登录');
                    if (!Laya.Browser.onPC) { var vConsole = new VConsole(); }
                    loginNormal(fun);
                    return;
                }
                if (param['xxCode']) {
                    LoginWeiXin(fun);
                    return
                }
            },
            wechatLogin: function (fun) {
                console.log('weChat登录');
                LoginWeiXin(fun);
            },
            checkGameUrl: function (fun) {
                loginByGuest({}, fun);
            },
        };
    };

    return {
        // 如果存在获取此单例实例，如果不存在创建一个单例实例
        getInstance: function () {
            if (!instance) {
                instance = init();
            }
            return instance;
        }
    };
})();
